﻿using IMES.Common.Domain.KeepModel.Process;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands.Defective
{
	public class DefectiveSumHandler : IRequestHandler<DefectiveSumCommand, Result>
	{
		private readonly IBaseRepositorys<Product> productRepository;
		private readonly IBaseRepositorys<ProcessRoute> processRouteRepository;
		private readonly IBaseRepositorys<WorkingProcedure> workingProcedureRepository;
		private readonly IBaseRepositorys<WType> wTypeRepository;

		public DefectiveSumHandler(IBaseRepositorys<Product> productRepository, IBaseRepositorys<ProcessRoute> processRouteRepository, IBaseRepositorys<WorkingProcedure> workingProcedureRepository, IBaseRepositorys<WType> wTypeRepository)
		{
			this.productRepository = productRepository;
			this.processRouteRepository = processRouteRepository;
			this.workingProcedureRepository = workingProcedureRepository;
			this.wTypeRepository = wTypeRepository;
		}

		public async Task<Result> Handle(DefectiveSumCommand request, CancellationToken cancellationToken)
		{
			var result = new Result() { Code = (int)CodeEnum.search };
			var res = (from a in productRepository.GetAll()
					   join b in processRouteRepository.GetAll() on a.ProcessRouteId equals b.ProcessRouteId
					   join c in workingProcedureRepository.GetAll() on b.ProcessRouteId equals c.ProcessRouteId
					   join d in wTypeRepository.GetAll() on c.WTypeId equals d.WTypeId
					   select new DefectiveSumDto()
					   {
						   ProcessRouteNumber = b.ProcessRouteNumber,
						   ProcessRouteName = b.ProcessRouteName,
						   ProductNumber = a.ProductNumber,
						   ProductName = a.ProductName,
						   ProductSpecification = a.ProductSpecification,
						   WorkingNumBer = c.WorkingNumBer
					   }).ToList();
			result.Data = res;
			return result;
		}
	}
}
